﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Nancy.Json;


namespace SOEI.Solution.Helper
{
    public class BusinessUtils
    {
        /// <summary>   身份证18位、15位互转
        /// </summary>
        /// <param name="oldCard"></param>
        /// <returns></returns>
        public static string GetCardID(string oldCard)
        {
            try
            {
                if (oldCard.Length == 18)
                {
                    //Bug #41945 2000年以后的18位身份证  不再尝试转换为 15位身份证
                    var vYear = 0;
                    if (int.TryParse(oldCard.Substring(6, 4), out vYear))
                    {
                        if (vYear >= 2000)
                            return oldCard;
                    }
                    string strZJHM = oldCard.Substring(0, 6) + oldCard.Substring(8, 9);
                    return strZJHM.ToUpper();
                }
                else if (oldCard.Length == 15)
                {
                    int[] w = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
                    string[] a = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };
                    string strZJHM = oldCard.Substring(0, 6) + "19" + oldCard.Substring(6);
                    int v_Sum = 0;
                    for (int i = 0; i < strZJHM.Length; i++)
                    {
                        v_Sum = v_Sum + int.Parse(strZJHM.Substring(i, 1)) * w[i];
                    }
                    int ai = v_Sum % 11;
                    strZJHM = strZJHM + a[ai];
                    return strZJHM.ToUpper();
                }
                else
                {
                    return oldCard;
                }
            }
            catch
            {
                return oldCard;
            }
        }
        public static string DataTable2Xml(DataTable pDt)
        {
            if (null == pDt)
                return "";
            DataSet ds = new DataSet("GridData");
            ds.Tables.Add(pDt.Copy());
            ds.Tables[0].TableName = "GridRow";
            string XML = ds.GetXml();
            ds.Tables.Clear();
            return XML;
        }

        /// <summary> 对象转换成JSON字符串
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="pObject"></param>
        /// <returns></returns>
        public static string ObjectToJson<TEntity>(TEntity pObject) where TEntity : class, new()
        {
            string vResult = string.Empty;
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            try
            {
                vResult = serializer.Serialize(pObject);
                if (vResult == "null")
                    vResult = string.Empty;
            }
            catch
            {
            }
            return vResult;
        }

        /// <summary>
        /// Json字符串首字母转大写
        /// </summary>
        /// <param name="strJsonData">json字符串</param>
        /// <returns></returns>
        public static string UpperFirst(string strJsonData)
        {
            MatchCollection matchCollection = Regex.Matches(strJsonData, "\\\"[a-zA-Z0-9]+\\\"\\s*:");
            foreach (Match item in matchCollection)
            {
                string res = Regex.Replace(item.Value, @"\b[a-z]\w+", delegate (Match match)
                {
                    string val = match.ToString();
                    return char.ToUpper(val[0]) + val.Substring(1);
                });
                strJsonData = strJsonData.Replace(item.Value, res);
            }
            return strJsonData;
        }

        /// <summary> 15与18位身份证相互转换
        /// </summary>
        /// <param name="pOldCard">身份证号码</param>
        /// <returns>转换后的身份证，15返回18，18返回15，不是身份证，返回原字符串。</returns>
        public static string ConverCardId(string pOldCard)
        {
            int[] vCoefficient = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
            char[] vEndNum = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };

            string vNewCard = string.Empty;

            if (pOldCard.Length == 15)
            {
                vNewCard = pOldCard.Insert(6, "19");
                var vTotal = 0;
                for (int i = 0; i < 17; i++)
                {
                    try
                    {
                        var vTemp = Convert.ToInt32(vNewCard.Substring(i, 1)) * vCoefficient[i];
                        vTotal += vTemp;
                    }
                    catch
                    {
                        return pOldCard;
                    }
                }

                vTotal %= 11;
                vNewCard += vEndNum[vTotal].ToString();
            }
            else if (pOldCard.Length == 18)
            {
                vNewCard = string.Format("{0}{1}", pOldCard.Substring(0, 6), pOldCard.Substring(8, 9));
            }
            else
            {
                vNewCard = pOldCard;
            }

            return vNewCard;
        }

        public static string HttpPostJsonAPI(string uri, string parameters, string token = "")
        {
            /*
             * @意向登记 parameters格式:{"GFYXDJSQBH":"1","PCBH":"1","DWBH":"1","DWMC":"1","LX":"01","JTCYXX":[{"JTZ":1,"ZJHM":"123456"},{"JTZ":2,"ZJHM":"9876542,3333333"}]}
             * @购房资格 parameters格式:{"SFZHLIST":"1234,2345"}
             */
            StreamReader reader = null;
            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(parameters);//这里需要指定提交的编码
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
                webRequest.Method = "POST";
                webRequest.ContentType = "application/json";
                webRequest.Accept = "application/json";
                webRequest.Headers.Add("token", token);
                webRequest.ContentLength = bytes.Length;
                Stream dataStream = webRequest.GetRequestStream();
                dataStream.Write(bytes, 0, bytes.Length);
                dataStream.Close();

                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
                string res = reader.ReadToEnd();
                return res.Trim();
            }
            catch (Exception ex)
            {

                throw;
            }
            finally
            {
                reader.Close();
            }
        }
    }
}
